package work.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import work.bean.RecordBorrowAndReturn;
import work.bean.WorkerFindHistory;
import work.entity.Book;
import work.entity.Bookware;
import work.entity.Borrow;
import work.service.BookService;
import work.service.BookwareService;
import work.service.BorrowService;
import work.service.CardService;
import work.vo.DataVo;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/borrow")
public class BorrowHandler {

    @Autowired
    private BorrowService borrowService;
    @Autowired
    private BookwareService bookwareService;
    @Autowired
    private CardService cardService;
    @Autowired
    private BookService bookService;

    // 续借图书，更新借阅表
    // 前端传入一个完整的借阅记录对象，必须包括所有的元素
    @PostMapping("/renew")
//    public DataVo renew(@RequestBody Borrow borrow) throws ParseException {
    public DataVo renew(@RequestBody String borrowId) throws ParseException {
        DataVo dataVo = new DataVo();

        Borrow borrow = borrowService.selectByBorrowId(borrowId);

        // 仅在状态为“正常”的情况下可以续借
        if (!borrow.getBorrowStatus().equals("正常")) {
            dataVo.setCode(150);
            dataVo.setMsg("目前该书不支持继借");
            return dataVo;
        }

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(borrow.getShouldDate());
        // 在应还日期处加一个月
        calendar.add(Calendar.MONTH, 1);
        borrow.setShouldDate(calendar.getTime());
        borrow.setBorrowStatus("续借");
        borrowService.updateBorrow(borrow);
        dataVo.setCode(151);
        dataVo.setMsg("续借成功");
        return dataVo;
    }

    // 工作人员查看借阅历史2，修改后
    // 前端传入一个workerFindHistory对象
    @PostMapping("/findHistory")
    public DataVo findHistory(@RequestBody WorkerFindHistory workerFindHistory) {
        DataVo dataVo = new DataVo();
        Borrow borrow = new Borrow();

        borrow.setBookId(workerFindHistory.getBookId());
        borrow.setUserId(workerFindHistory.getUserId());
        if (workerFindHistory.getUserId() == "" && workerFindHistory.getBookId() == "" && workerFindHistory.getBookName() != ""){
            String s = "%" + bookwareService.findIdByName(workerFindHistory.getBookName()) + "%";
            workerFindHistory.setBookId(s);
        }
        List<Borrow> borrowList = borrowService.selectSomeBorrow(borrow);
        if (borrowList.isEmpty()) {
            dataVo.setCode(260);
            dataVo.setMsg("借阅历史中没有对应的记录");
        } else {
            dataVo.setCode(261);
            dataVo.setMsg("借阅历史中存在多条记录");
            dataVo.setData(borrowList);
        }
        return dataVo;
    }

    // 工作人员登记读者借书信息2，修改后
    // 前端传入recordBorrowAndReturn对象
    @PostMapping("/recordBorrow")
    public DataVo recordBorrow(@RequestBody RecordBorrowAndReturn recordBorrowAndReturn) throws ParseException {
        DataVo dataVo = new DataVo();
        Borrow borrow = new Borrow();
        Book book = new Book();
        String cardId = recordBorrowAndReturn.getCardId();
        String bookId = recordBorrowAndReturn.getBookId();

        // 根据传入的库存编号查找一个对象，存在则说明该书存在
        Bookware bookware = bookwareService.findById(recordBorrowAndReturn.getBookId().substring(0, 11));
        if (bookware.getBookTotal() - bookware.getBookLending() == 0) {
            dataVo.setCode(140);
            dataVo.setMsg("没有可以借阅的图书");
            return dataVo;
        }
        // 更新lending
        bookware.setBookLending(bookware.getBookLending() + 1);
        int a1 = bookwareService.updateWare(bookware);

        String s = cardService.selectStatusByCardId(cardId);
        if (!s.equals("正常")) {
            dataVo.setCode(270);
            dataVo.setMsg("该借阅证状态为：" + s + "，不可进行借书操作");
            return dataVo;
        }
        s = bookService.selectStatusByBookId(bookId);
        if (!s.equals("可借")) {
            dataVo.setCode(271);
            dataVo.setMsg("该书状态为：" + s + "，不可进行借书操作");
            return dataVo;
        }
        borrow.setBorrowId(String.valueOf(System.currentTimeMillis()));
        borrow.setBookId(bookId);
        borrow.setUserId(cardId.substring(0, 11));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date now = new Date();
        borrow.setBorrowDate(simpleDateFormat.parse(simpleDateFormat.format(now)));
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.add(Calendar.MONTH, 1);
        borrow.setShouldDate(calendar.getTime());
        // 设置应还日期，即在借书日期基础上加上一个月
        borrow.setBorrowStatus("正常");
        // 设置借阅状态
        int a = borrowService.insertBorrow(borrow);
        // 更新数据库
        // 更新status
        book.setBookId(borrow.getBookId());
        book.setBookStatus("外借");
        // 设置该书对应的状态为“外借”
        int b = bookService.updatebookStatus1(book);
        // 更新数据库
        if (a == 0 || b == 0) {
            dataVo.setCode(272);
            dataVo.setMsg("借书失败");
        } else {
            dataVo.setCode(273);
            dataVo.setMsg("借书成功");
        }
        return dataVo;
    }

    // 工作人员登记读者还书信息2，修改后
    // 前端传入一个cardId字符串、一个bookId字符串和一个status状态字符串（即损坏和丢失，其余情况为空即可，超期后台会自动判断）
    @PostMapping("/recordReturn")
    public DataVo recordReturn(@RequestBody RecordBorrowAndReturn recordBorrowAndReturn) throws ParseException {
        DataVo dataVo = new DataVo();
        String cardId = recordBorrowAndReturn.getCardId();
        String bookId = recordBorrowAndReturn.getBookId();
        String status = recordBorrowAndReturn.getStatus();

        // 根据传入的库存编号查找一个对象，存在则说明该书存在
        Borrow borrow = borrowService.selectByUserIdAndBookId(cardId.substring(0, 11), bookId);
        // 根据用户id和图书id查询出一个借阅记录
        Bookware bookware = bookwareService.findById(bookId.substring(0, 11));
        // 更新lending
        bookware.setBookLending(bookware.getBookLending() - 1);
        bookware.setBookHistory(bookware.getBookHistory() + 1);
        int a11 = bookwareService.updateWare(bookware);

        // 借阅记录不存在
        if (borrow == null) {
            dataVo.setCode(280);
            dataVo.setMsg("此借阅记录不存在，请检查输入信息是否正确");
            return dataVo;
        }
        // 设置实际还书日期和借阅状态（默认为归还，具体情况下面再判断）
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date now = new Date();
        now = simpleDateFormat.parse(simpleDateFormat.format(now));
        borrow.setRealDate(now);
        borrow.setBorrowStatus("归还");
        // 处理损坏或丢失，罚款金额为图书原价，状态默认为未缴纳罚款
        if (status.equals("损坏")) {
            borrow.setPunishmentType("损坏");
            borrow.setPunishmentPrice(bookware.getBookPrice());
            borrow.setPunishmentStatus("N");
            dataVo.setCode(281);
            dataVo.setMsg("该图书已损坏");
        } else if (status.equals("丢失")) {
            borrow.setPunishmentType("丢失");
            borrow.setPunishmentPrice(bookware.getBookPrice());
            borrow.setPunishmentStatus("N");
            dataVo.setCode(282);
            dataVo.setMsg("该图书已丢失");
        } else {
            // 图书正常归还
            // 判断是否超期
            if (now.before(borrow.getShouldDate())) {
                borrow.setPunishmentType("不处罚");
                dataVo.setCode(283);
                dataVo.setMsg("图书在规定时间内归还");
            } else {
                borrow.setBorrowStatus("超期");
                borrow.setPunishmentType("超期");
                // 超期罚款0.2元/天
                Double d = 0.2 * ((now.getTime() - borrow.getShouldDate().getTime()) / (60 * 60 * 24 * 1000));
                BigDecimal bg = new BigDecimal(d);
                d = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); // 化为两位小数的形式
                borrow.setPunishmentPrice(d);
                borrow.setPunishmentStatus("N");
                dataVo.setCode(284);
                dataVo.setMsg("图书超期归还");
            }
        }
        int i = borrowService.updateBorrow(borrow);
        List<Borrow> borrowList = new ArrayList<>();
        borrowList.add(borrow);
        dataVo.setData(borrowList);
        return dataVo;
    }


    // 查看罚款历史2，修改后
    // 前端传入一个borrow对象即可
    @PostMapping("/findFine")
    public DataVo findFine(@RequestBody Borrow borrow) {
        DataVo dataVo = new DataVo();
        List<Borrow> borrowList = borrowService.selectSomeBorrow1(borrow);
        if (borrowList.isEmpty()) {
            dataVo.setCode(290);
            dataVo.setMsg("没有对应的罚款记录");
            return dataVo;
        }
        dataVo.setCode(291);
        dataVo.setMsg("存在对应的罚款记录");
        dataVo.setData(borrowList);
        return dataVo;
    }


    // 工作人员缴纳罚款管理
    // 前端传入该罚款记录对应的borrowId
    @PostMapping("/payFine")
    public DataVo payFine(@RequestBody String borrowId) {
        DataVo dataVo = new DataVo();

        Borrow borrow = new Borrow();
        borrow.setBorrowId(borrowId);
        borrow.setPunishmentStatus("Y");

        int i = borrowService.updateBorrow(borrow);

        if (i == 0) {
            dataVo.setCode(350);
            dataVo.setMsg("缴纳罚款失败");
        } else {
            dataVo.setCode(351);
            dataVo.setMsg("缴纳罚款成功");
        }
        return dataVo;
    }

    // 工作人员查看图书催还表
    // 前端传入一个userId字符串即可
    @PostMapping("/findOverdue")
    public DataVo findOverdue(@RequestBody String userId) {
        DataVo dataVo = new DataVo();

        List<Borrow> borrowList = borrowService.selectByUser(userId);
        if (borrowList.isEmpty()) {
            dataVo.setCode(300);
            dataVo.setMsg("没有对应的借阅记录");
            return dataVo;
        }

        Date now = new Date();
        List<Borrow> borrowList1 = new ArrayList<>();
        for (Borrow borrow: borrowList) {
            if (!now.before(borrow.getShouldDate())) {
                borrow.setBorrowStatus("超期");
                borrowList1.add(borrow);
            }
        }

        if (borrowList1.isEmpty()) {
            dataVo.setCode(301);
            dataVo.setMsg("不存在超期记录");
        } else {
            dataVo.setCode(302);
            dataVo.setMsg("存在超期的借阅记录");
            dataVo.setData(borrowList1);
        }
        return dataVo;
    }
}
